package jzoffer;

/**
 * @author MaoLin Wang
 * @date 2020/10/9 2:59 下午
 */
public class _29顺时针打印矩阵 {
    /*
         left =0; right =m[0].len;top=0;bottom=m.len
          while(true){
             print(left++,top) --> left>right-1?break; left=right-1;

            print(right,top--) ---> top>bottom-1? break; top=bottom-1;

            print()


          }
     */
    public static int[] spiralOrder(int[][] matrix) {
        if (matrix==null){
            return new int[]{};
        }
        if (matrix.length==1){
            return matrix[0];
        }
        int[]res=new int[matrix.length*matrix[0].length];
        int index=0;

        int left=0,right=matrix[0].length-1;
        int top=0,bottom=matrix.length-1;

        while (true){
            int temp=left;
            // 左 → 右

            while (left<=right){
                   res[index++]=matrix[top][left];
                   left++;

            }
            if (left>right){
                left=temp;
            }
            if (++top> bottom){
                break;
            }

            temp=top;
            // 上  ->  下
            while (top <= bottom){
                res[index++]=matrix[top][right];
                top++;
            }

            if (top>bottom){
                top=temp;
            }
            if (--right<left){
                break;
            }

            temp=right;
            //右  --> 左
            while (right>=left){
                res[index++]=matrix[bottom][right];
                right--;
            }
            //下边界向上移动一个
            if (--bottom<top){
                break;
            }
            if (right<left){
                right=temp;
            }

            //下  -->  上
            temp=bottom;
            while (bottom >= top){
                res[index++]=matrix[bottom][left];
                bottom--;
            }
            if (bottom<=top){
                bottom=temp;
            }
           if (++left>right){
               break;
           }

        }
        return res;

    }

    public static void main(String[] args) {
        int[][] matrix = new int[3][3];
        matrix[0][0]=1;
        matrix[0][1]=2;
        matrix[0][2]=3;
        matrix[1][0]=4;
        matrix[1][1]=5;
        matrix[1][2]=6;
        matrix[2][0]=7;
        matrix[2][1]=8;
        matrix[2][2]=9;
        int[] ints = spiralOrder(matrix);
        for (int i : ints) {
            System.out.println(i);
        }
    }
}
